from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher.filters.state import State, StatesGroup

import sqlite_db
from config import Settings
from keyboards import admin_kb
from main import dp


class FSMAdmin(StatesGroup):
    go_amount = State()
    promo_name = State()
    promo_discount = State()
    promo_del = State()
    mail = State()
    mail_go = State()


async def admin_cancel(message: types.Message, state: FSMContext):
    current_state = await state.get_state()
    if current_state is None:
        return
    await state.finish()
    await admin_command(message)


@dp.callback_query_handler(Text(equals="cancel_admin"), state="*")
async def admin_cancel_inline(callback: types.CallbackQuery, state: FSMContext):
    current_state = await state.get_state()
    if current_state is None:
        return
    await state.finish()
    user_id = callback.from_user.id
    await sqlite_db.sql_admin_command(user_id)


@dp.message_handler(Text(equals=["/admin", "Назад в меню"]))
async def admin_command(message: types.Message, config: Settings):
    if int(message.from_user.id) in config.tg_bot.admin_ids:
        user_id = message.from_user.id
        await sqlite_db.sql_admin_command(user_id)
    else:
        pass


@dp.message_handler(Text(equals="Выдать фото вручную"), state=None)
async def command_give_acc(message: types.Message, config: Settings):
    if int(message.from_user.id) in config.tg_bot.admin_ids:
        await message.bot.send_message(
            message.from_user.id,
            "отправь ID человека",
            reply_markup=admin_kb.kb_admin_cancel,
        )
        await FSMAdmin.go_amount.set()


@dp.message_handler(state=FSMAdmin.go_amount)
async def command_give_acc_go(
    message: types.Message, state: FSMContext, config: Settings
):
    if int(message.from_user.id) in config.tg_bot.admin_ids:
        user = message.text
        if user.isdigit():
            await sqlite_db.sql_command_give_acc_go(state, message, user)
        else:
            await message.bot.send_message(
                message.from_user.id,
                "нужно ввести цифру",
                reply_markup=admin_kb.kb_admin_cancel,
            )


@dp.message_handler(Text(equals="Промокоды"))
async def admin_promo(message: types.Message, config: Settings):
    if int(message.from_user.id) in config.tg_bot.admin_ids:
        await sqlite_db.sql_admin_promo(message)
    else:
        pass


@dp.callback_query_handler(Text(equals="promo_give"), state=None)
async def admin_promo_give(callback: types.CallbackQuery):
    await callback.bot.send_message(
        callback.from_user.id,
        "отправь название промокода",
        reply_markup=admin_kb.kb_admin_cancel,
    )
    await FSMAdmin.promo_name.set()


@dp.message_handler(state=FSMAdmin.promo_name)
async def admin_promo_give_name(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        data["promo_name"] = message.text
    await message.bot.send_message(
        message.from_user.id,
        "Укажи сколько процентов скидки действует с этим промокодом (цифрой)",
        reply_markup=admin_kb.kb_admin_cancel,
    )
    await FSMAdmin.promo_discount.set()


@dp.message_handler(state=FSMAdmin.promo_discount)
async def admin_promo_give_discount(
    message: types.Message, state: FSMContext
):
    promo_discount = message.text
    if promo_discount.isdigit():
        async with state.proxy() as data:
            data["promo_discount"] = promo_discount
        print(data)
        await sqlite_db.sql_admin_add_promo(message, state)
    else:
        await message.bot.send_message(
            message.from_user.id,
            "нужно ввести цифру",
            reply_markup=admin_kb.kb_admin_cancel,
        )


@dp.callback_query_handler(Text(equals="promo_del"), state=None)
async def admin_promo_del(callback: types.CallbackQuery):
    await callback.bot.send_message(
        callback.from_user.id,
        "отправь id промокода, который нужно удалить",
        reply_markup=admin_kb.kb_admin_cancel,
    )
    await FSMAdmin.promo_del.set()


@dp.message_handler(state=FSMAdmin.promo_del)
async def admin_promo_del_go(message: types.Message, state: FSMContext):
    promo_del = message.text
    if promo_del.isdigit():
        await sqlite_db.sql_admin_delete_promo(message, state, promo_del)
    else:
        await message.bot.send_message(
            message.from_user.id,
            "нужно ввести цифру",
            reply_markup=admin_kb.kb_admin_cancel,
        )


@dp.message_handler(Text(equals="Сделать рассылку"))
async def admin_mail(message: types.Message, config: Settings):
    if int(message.from_user.id) in config.tg_bot.admin_ids:
        await message.bot.send_message(
            message.from_user.id,
            "Отправь одним сообщением что нужно разослать\n"
            "(картинка или gif с текстом, либо просто текст)",
            reply_markup=admin_kb.kb_admin_cancel,
        )
        await FSMAdmin.mail.set()


@dp.message_handler(content_types=types.ContentTypes.ANY, state=FSMAdmin.mail)
async def admin_mail_confirm(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    if message.document:
        async with state.proxy() as data:
            data["mail_doc"] = message.document["mime_type"]
            data["mail_doc_file_id"] = message.document["file_id"]
            data["caption"] = message.caption
            data["entities"] = message.caption_entities
        mime_check = data["mail_doc"]
        if (mime_check.split("/", 1)[0]) == "image":
            await message.bot.send_message(
                message.from_user.id,
                "Нужно отправить сжатое изображение (картинкой)",
                reply_markup=admin_kb.kb_admin_cancel,
            )
        else:
            await message.bot.send_message(
                message.from_user.id,
                "Сообщение выше будет отпралено всем пользователям бота, начать рассылку?",
                reply_markup=admin_kb.kb_admin_mail_go,
            )
            await FSMAdmin.mail_go.set()
    elif message.photo:
        async with state.proxy() as data:
            data["mail_doc"] = "just_photo/"
            data["mail_doc_file_id"] = message.photo[0].file_id
            data["caption"] = message.caption
            data["entities"] = message.caption_entities
            await message.bot.send_message(
                message.from_user.id,
                "Сообщение выше будет отпралено всем пользователям бота, начать рассылку?",
                reply_markup=admin_kb.kb_admin_mail_go,
            )
            await FSMAdmin.mail_go.set()
    elif message.text:
        async with state.proxy() as data:
            data["mail_doc"] = "text/"
            data["mail_doc_file_id"] = "none"
            data["caption"] = message.text
            data["entities"] = message.entities
            await bot.send_message(
                message.from_user.id,
                "Сообщение выше будет отпралено всем пользователям бота, начать рассылку?",
                reply_markup=admin_kb.kb_admin_mail_go,
            )
            await FSMAdmin.mail_go.set()
    elif message.video:
        await bot.send_message(
            message.from_user.id,
            "Отправлено видео, а нужно отправить картинку или gif с текстом, либо просто текст",
            reply_markup=admin_kb.kb_admin_cancel,
        )


@dp.callback_query_handler(Text(equals="mail_go"), state=FSMAdmin.mail_go)
async def admin_mail_go(callback: types.CallbackQuery, state: FSMContext):
    user_id = callback.from_user.id
    async with state.proxy() as data:
        mime_check = data["mail_doc"]
        mail_doc_file_id = data["mail_doc_file_id"]
        caption = data["caption"]
        entities = data["entities"]
        await state.finish()
        await callback.bot.send_message(
            user_id, "идет рассылка...", reply_markup=admin_kb.admin_menu
        )
        await sqlite_db.sql_admin_mail_sendind(
            user_id, mime_check, mail_doc_file_id, caption, entities
        )
